package com.bank.bincode.service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bank.bincode.dao.BankDAO;
import com.bank.bincode.model.Bank;
import com.bank.bincode.model.BankExample;
import com.bank.bincode.model.BankExample.Criteria;


/******************************************************************************************************************
 *
 * 银行卡查询服务
 * 
 * @author junrong
 * @date 2016年8月17日 下午4:46:02
 * @version 1.0
 *****************************************************************************************************************/
@Service("bankService")
public class BankService {

	@Autowired
	private BankDAO bankDAO;

	/**
	 * 根据银行卡号查询银行信息
	 * 
	 * @param card
	 *            银行卡号
	 * @return
	 */
	public Bank getBankByCard(String card) {

		if (card == null || card.trim().length() < 15) {
			return null;
		}
		BankExample example = new BankExample();
		Criteria criteria = example.createCriteria();
		criteria.andBinValueEqualTo(card.substring(0, 6));
		List<Bank> banks = bankDAO.selectByExample(example);
		if (banks == null || banks.size() < 1) {
			criteria.andBinValueEqualTo(card.substring(0, 5));
			banks = bankDAO.selectByExample(example);
			if (banks == null || banks.size() < 1) {
				criteria.andBinValueEqualTo(card.substring(0, 7));
				banks = bankDAO.selectByExample(example);
				if (banks == null || banks.size() < 1) {
					criteria.andBinValueEqualTo(card.substring(0, 8));
					banks = bankDAO.selectByExample(example);
					if (banks == null || banks.size() < 1) {
						criteria.andBinValueEqualTo(card.substring(0, 9));
						banks = bankDAO.selectByExample(example);
					}
				}
			}
		}

		if (!banks.isEmpty()) {
			Collections.sort(banks, new Comparator<Bank>() {

				@Override
				public int compare(Bank o1, Bank o2) {

					return o2.getBinLength() - o1.getBinLength();
				}
			});
		}

		return (banks != null && banks.size() > 0) ? banks.get(0) : null;
	}

	public static void main(String[] args) {
		String s = "0123456789";
		System.out.println(s.substring(0, 6));
	}
}
